package com.itheima.health.h5.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.itheima.health.pojo.Order;
import com.itheima.health.service.OrderService;
import com.itheima.health.utils.date.DateUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
public class PayController {
    //支付宝服务器地址
    String SERVERURL = "https://openapi.alipaydev.com/gateway.do";
    //商户appid
    String APP_ID = "2021000116677844";
    //商户私钥
    String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC5gHZLKJMLohv+kPMOFHxImSt2J9GaKWnW0Imup3Pltnw9MCl/CqE5xzNeHvfV+2qSZV02FDMXvyLbW0hWb8gtMLaQzQsshziIvqUSMzh+NnArqmXgj/Cyfaj8sk0DAKdOdrbfyh8NVEjqDT2jJGzdbObwNg3sGgyaXfNcucgS85k2A7o0CyWeFCneNTTM3YijyikbTiuJSaBsJorNRV1zm/CqUyexYq+ta9U89Ys6oxFenWnkVvHW7A3yeyvDVZ/ZOksaNCyxT8kuRtbpqSv5rNg2UpXWI2mN85vabf4ZGEXtQOXpSUtPi6/jsE1Dg66kcrOAxMI4JE/fNJnReCevAgMBAAECggEAWnwvN7ozABmzThmmddfISCFu8dO6ilhpKD/Q6UEFZ6f8Mlyr4SxuOKDSjbbNbbOV6JNJRHfV9F9nwVhlkMQ2ANUiOL/ME4xiJ1HXc2lIxUgIr0QPLdsIrghdxeWzayOGeN+vlLojK31Rk9mhl1LNR7U3cTTs1Z5fR21MqI526cbSXV19yhRT23nQVaFII3p2wPuoUvEnAB6H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QEFAAOCAQ8AMIIBCgKCAQEAl7jEo0wb+zKqwn9UqNiRUMsWhGVfuieHxsHAiyoKC42P1BT/MA4jXqqkmgEjAFxYKkeNDyNZQt/Z+rWiJD8wT+ShkqqFdTf6Q3yiy28fOYrf7LW/4j8HV1fqeJdAyd96GUUpMiDr8CVDmcWt6oe3WF/LUEhZWPImmWV1OaA9vCdYcB344ijFwiO8pvvrTN1pALgzE+9RJsceWsuAb8u0OX7dIy8Vvk9x2E11ofbqXcZGqp8eNIE4e0OcRTJCZeK79BZi3DeOyB4csh2tSXVh2+xfg+XU8c34DfyhsWD/HZLl72SD/yUaq+7JSi1cNz3/F2TW2syK028VLOb71T/JPQIDAQAB";
    @Reference
    private OrderService orderService;

    /**
     * 构造支付请求
     *
     * @param httpRequest
     * @param httpResponse
     * @param orderId
     * @throws ServletException
     * @throws IOException
     */
    @GetMapping("pay/aliPay/{id}")
    public void alipay(HttpServletRequest httpRequest,
                       HttpServletResponse httpResponse, @PathVariable("id") Integer orderId) throws ServletException, IOException {
        AlipayClient alipayClient =
                new DefaultAlipayClient(SERVERURL,
                        APP_ID, APP_PRIVATE_KEY,
                        "json",
                        CHARSET,
                        ALIPAY_PUBLIC_KEY, "RSA2"); //获得初始化的AlipayClient

        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
        alipayRequest.setReturnUrl("http://localhost:8082/pages/orderSuccess.html?id="+orderId);//支付成功之后跳转的地址(由于我们没有域名,我们使用natapp内网穿透工具)
        alipayRequest.setNotifyUrl("http://zeqa8s.natappfree.cc/pay/alipayNotify/"+orderId);//支付成功通知地址
        String orderNum = outTradeNo(orderId);
        Order order = new Order();
        order.setId(orderId);

        order.setOrderNum(orderNum);
        Map orderInfo = orderService.findOrderInfoById(orderId);
        orderService.updateById(order);
        JSONObject json = new JSONObject();
        json.put("out_trade_no", orderNum);//商户订单号，需要保证不重复(支付回调会带上这个参数，我们可以用来查询对应的订单修改状态)
        json.put("total_amount", 0.01);//订单金额
        json.put("subject", orderInfo.get("setmeal")/*"随便一个套餐"*/);//订单标题
        alipayRequest.setBizContent(json.toJSONString());

        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /**
     * 生成商户订单号（年月日时分秒 + 订单号）
     *
     * @param orderId
     * @return
     */
    private String outTradeNo(Integer orderId) {
        String dateStr = DateUtils.parseDate2String(new Date(), "yyyyMMddHHmmss");
        return dateStr + orderId;
    }

    /**
     * 支付宝通知我们支付状态，在这个接口里面可以修改订单支付的状态
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping("pay/alipayNotify/{id}")
    @ResponseBody
    public String alipayNotify(HttpServletRequest request, HttpServletRequest response ,@PathVariable("id") Integer orderId) throws Exception {
        System.out.println("这个方法启动了吗");
        Order order = new Order();
        order.setIs_pay(1);
        order.setId(orderId);
        orderService.updateById(order);
//        log.info("支付成功, 进入异步通知接口...");

        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2"); //调用SDK验证签名
        //——请在这里编写您的程序（以下代码仅作参考）——
		/* 实际验证过程建议商户务必添加以下校验：
		1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
		2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
		3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
		4、验证app_id是否为该商户本身。
		*/
        if (signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            if (trade_status.equals("TRADE_FINISHED")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意： 尚自习的订单没有退款功能, 这个条件判断是进不来的, 所以此处不必写代码
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知

                // 修改叮当状态，改为 支付成功，已付款; 同时新增支付流水
            }
//            log.info("支付成功...");
        } else {//验证失败
//            log.info("支付, 验签失败...");
        }

        return "success";
    }
}
